import Vue from 'vue';
import axios from 'axios';
import { Toast } from 'vant';

Vue.use(Toast);
let requestCount = 0;
let toast = null;
// 用于存下所有已发生的请求，并在合适的时候进行cancel
let requests = [];

function showLoading(loadTxt) {
	if (requestCount === 0) {
		toast = Toast.loading({
			duration: 0, // 持续展示 toast
			forbidClick: true, // 禁用背景点击
			loadingType: 'spinner', //circular,
			message: loadTxt || '',
		});
	}
	requestCount++;
}
// 隐藏loading
function hideLoading() {
	setTimeout(() => {
		if (requestCount <= 0) return false;
		requestCount--;
		if (requestCount === 0) {
			if (toast) {
				toast.clear();
				toast = null;
			}
		}
	}, 0);
}

function showToast(msg) {
	if (toast) {
		toast.clear();
		toast = null;
	}
	Toast(msg);
}
// create an axios instance
let service = axios.create({
	baseURL: '/', // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 500000, // request timeout
});
service.cancelAll = function() {
	requests.forEach((ele, index) => {
		ele.cancel();
		delete requests[index];
	});
};
// request interceptor
service.interceptors.request.use(
	(config) => {
		// do something before request is sent
		let token = localStorage.getItem('token');
		if (token) {
			config.headers['token'] = token;
		}
		if (!config.noToast) showLoading('加载中...');
		config.cancelToken = new axios.CancelToken((cancel) => {
			requests.push({
				cancel,
			});
		});
		return config;
	},
	(error) => {
		// do something with request error
		console.log(error); // for debug
		hideLoading();
		return Promise.reject(error);
	}
);

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	(response) => {
		hideLoading();
		return response.data;
	},
	(error) => {
		console.log('err' + error); // for debug
		hideLoading();
		showToast('服务器故障或网络超时，请检查网络');
		return Promise.reject(error);
	}
);

export default service;
